package gateway.config;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
import org.springframework.context.event.EventListener;

import javax.annotation.PostConstruct;
import java.util.concurrent.Executor;

@Configuration
@RefreshScope
public class NacosConfiguration {
    
    private static final Logger logger = LoggerFactory.getLogger(NacosConfiguration.class);

    @Value("${spring.cloud.nacos.config.server-addr}")
    private String serverAddr;//127.0.0.1:8848

    @Value("${spring.cloud.nacos.config.namespace}")
    private String namespace;

    @Value("${spring.application.name}")
    private String applicationName;

    @Value("${spring.profiles.active}")
    private String activeProfile;

    @PostConstruct
    public void init() {
        try {
            ConfigService configService = NacosFactory.createConfigService(serverAddr);
            
            // 构建Data ID
            String dataId = applicationName + "-" + activeProfile + ".yml";
            logger.info("正在监听Nacos配置，Data ID: {}", dataId);
            
            // 添加配置监听器
            configService.addListener(dataId, namespace, new Listener() {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    logger.info("收到Nacos配置更新通知");
                    logger.info("Data ID: {}", dataId);
                    logger.info("新的配置内容: {}", configInfo);
                }

                @Override
                public Executor getExecutor() {
                    return null;
                }
            });
            
            logger.info("Nacos配置监听器初始化成功");
        } catch (NacosException e) {
            logger.error("Nacos配置监听器初始化失败", e);
        }
    }

    @EventListener
    public void onRefreshScopeRefreshed(RefreshScopeRefreshedEvent event) {
        logger.info("配置刷新事件触发");
        try {
            // 重新获取 ConfigService 实例
            ConfigService configService = NacosFactory.createConfigService(serverAddr);
            String dataId = applicationName + "-" + activeProfile + ".yml";
            
            // 获取最新的配置内容
            String config = configService.getConfig(dataId, namespace, 5000);
            logger.info("刷新后的配置内容 - Data ID: {}", dataId);
            logger.info("配置内容:\n{}", config); // 使用 \n 使配置内容换行打印，更清晰
        } catch (NacosException e) {
            logger.error("获取刷新后的Nacos配置失败", e);
        }
    }
} 